package com.lcc.forum.demos.web.services.impl;

import com.lcc.forum.demos.web.common.AppResult;
import com.lcc.forum.demos.web.common.ResultCode;
import com.lcc.forum.demos.web.dao.ArticleMapper;
import com.lcc.forum.demos.web.exception.ApplicationException;
import com.lcc.forum.demos.web.model.Article;
import com.lcc.forum.demos.web.model.Board;
import com.lcc.forum.demos.web.model.User;
import com.lcc.forum.demos.web.services.IArticleService;
import com.lcc.forum.demos.web.services.IBoradService;
import com.lcc.forum.demos.web.services.IUserService;
import com.lcc.forum.demos.web.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private IUserService userService;
    @Resource
    private IBoradService boradService;
    @Resource
    private ArticleMapper articleMapper;
    @Override
    public void create(Article article) {
        //校验参数的合法性
        if (article == null || article.getUserId() == null
                || article.getBoardId() == null
                || article.getTitle() == null
                || article.getContent() == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //配置默认值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //将该文章插入到文章表中
        int articleRow = articleMapper.insert(article);
        //校验是否操作成功
        if (articleRow <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //操作成功后，更新用户和版块的发帖数量和帖子数量
        //首先需要校验该用户是否存在
        User user = userService.selectById(article.getUserId());
        //没有找到指定用户信息
        if (user == null){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败, user id = " + article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //用户存在，更新用户的发帖数量
        userService.addOneArticleCountById(user.getId());
        //校验版块是否存在
        Board board = boradService.selectById(article.getBoardId());
        //没有找到版块信息
        if (board == null){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败, board id = " + article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //版块存在，更新版块的帖子数量
        boradService.addOneArticleCountById(board.getId());
        //操作成功，打印日志
        log.info(ResultCode.SUCCESS.toString() + ",user id = "  + article.getUserId() +
                ",board id = " + article.getBoardId() + ",article id = " +
                article.getId() + "发帖成功");
//        throw new ApplicationException("测试回滚");
    }

    /**
     * 查询所有的帖子
     * @return
     */
    @Override
    public List<Article> selectAll(){
        //调用DAO
        List<Article> articles = articleMapper.selectAll();
        //此处不需要校验，谁用谁校验
        return articles;
    }

    /**
     * 查看特定版块的帖子列表
     * @param boardId 版块id
     * @return
     */
    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //校验boardId参数
        if (boardId == null || boardId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验版块是否存在
        Board board = boradService.selectById(boardId);
        if (board == null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //查询帖子列表
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询对应的帖子对象
        Article article = articleMapper.selectDetailById(id);
        //校验帖子对象是否有效
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子的访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        //保存到数据库：完成下面这句代码之后数据库中的帖子的访问次数就加了1
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验操作是否成功
        if (row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新返回对象的访问次数：因为此处如果直接返回article，这个article的访问次数并没有更新
        article.setVisitCount(article.getVisitCount() + 1);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //参数非空校验
        if(id == null || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子
        //构造要更新的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验是否操作成功
        if (row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Article selectById(Long id) {
        //校验参数有效性
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //调用DAO查询
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //参数校验
        if (userId == null || userId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if (user == null || user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用DAO
        List<Article> articles = articleMapper.selectByUserId(userId);
        //返回结果
        return articles;
    }

    @Override
    public void thumbsUpById(Long id) {
        //参数非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验帖子是否存在
        if (article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //校验帖子状态是否正确
        if (article.getState() == 1 ){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //更新帖子的点赞数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        //调用DAO方法
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验是否操作成功
        if (row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //打印日志
        log.info("点赞成功");
    }

    /**
     * 删除帖子
     * @param id 要删除帖子的id
     */
    @Override
    public void deleteById(Long id) {
        //参数非空校验
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //对帖子进行校验
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            //打印帖子不存在的日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1){
            //打印帖子禁用日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造一个对象更新帖子的deleteState
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验操作是否执行成功
        if (row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新版块中的帖子数量
        boradService.subOneArticleCountById(article.getBoardId());
        //更新用户的发帖数量
        userService.subOneArticleCountById(article.getUserId());
        //执行成功，打印日志
        log.info("删除帖子成功, article id = " + article.getId() + ",user id = " + article.getUserId() + ".");
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //参数有效性校验
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //校验帖子状态
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1){
            //打印帖子不存在的日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1){
            //打印帖子禁用日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //创建更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        //回复数 = 原回复数 + 1
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());
        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验操作结果
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
}
